package com.example.android.newsreader.previo.servicio;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

import org.apache.http.client.ClientProtocolException;

import com.example.android.newsreader.previo.MainActivity;
import com.example.android.newsreader.R;
import com.example.android.newsreader.previo.base.ManagerDB;
import com.example.android.newsreader.previo.clases.Imagen;
import com.google.gson.Gson;

import com.dropbox.client2.DropboxAPI;
import com.dropbox.client2.ProgressListener;
import com.dropbox.client2.DropboxAPI.Entry;
import com.dropbox.client2.android.AndroidAuthSession;
import com.dropbox.client2.exception.DropboxException;
import com.dropbox.client2.session.AppKeyPair;
import com.dropbox.client2.session.Session.AccessType;

import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Environment;

import android.os.Vibrator;
import android.widget.RemoteViews;
import android.widget.Toast;

public class Servico2UpdatePictures extends IntentService {
	final static private String APP_KEY = "gn6mw3jxqv771rv";
	final static private String APP_SECRET = "xxct423x3zs3840";
	final static private AccessType ACCESS_TYPE = AccessType.DROPBOX;

	File sdCard = Environment.getExternalStorageDirectory();
	final static private String ACCOUNT_PREFS_NAME = "prefs";
	final static private String ACCESS_KEY_NAME = "ACCESS_KEY";
	final static private String ACCESS_SECRET_NAME = "ACCESS_SECRET";
	DropboxAPI<AndroidAuthSession> mDBApi;
	NotificationManager mNM;
	ManagerDB manager;

	public Servico2UpdatePictures() {
		super("Servico2UpdatePictures");

	}

	@Override
	public void onCreate() {
		super.onCreate();
		mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

	
		showNotification("Cargando", (int) 100, (int) 0, new File(""));
		AndroidAuthSession session = buildSession();
		mDBApi = new DropboxAPI<AndroidAuthSession>(session);
		manager = new ManagerDB(this);

	}

	@Override
	protected void onHandleIntent(Intent intent) {

		inicio(manager.getImagenToUpload());

	}

	public void inicio(Imagen img) {
		if (img != null) {
			Toast.makeText(this, img.getUrl(), Toast.LENGTH_SHORT).show();
			if (uploadfile(img.getUrl(), img.getAplicacion().getCliente()
					.getCarpetaImagenes()
					+ img.getAplicacion().getPrevio().getReferencia()
					+ "/"
					+ img.getNombre() + ".jpg")) {
				
				manager.updateImagenEstado(img.getIdImagen());
				if (img.getTipo().getIdTipo() == 1) {
					generateInsidencias(new File(img.getUrl()), img);

				}
                if(manager.getTotalImagenesByApplicacion(img.getAplicacion().getIdAplicacion())==1){
                	try {
                		img.getAplicacion().setEstado("3");
						manager.changeEstado("http://192.168.1.71:8080/codeigniter_2.1.3/index.php/webservice/Webservice/changestatus",new Gson().toJson(img.getAplicacion()));
					} catch (ClientProtocolException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
                }
                
				Imagen aux = manager.getImagenToUpload();
				inicio(aux);

			} else {
				mNM.cancel(R.string.hello_world);
				// stopForeground(true);
				Vibrator v = (Vibrator) getSystemService(VIBRATOR_SERVICE);
				v.vibrate(500);
				showNotificationError("Error!..Reintentar Envio! "
						+ img.getNombre());
				stopSelf();
			}

		} else {
			mNM.cancel(R.string.hello_world);
			// stopForeground(false);
			stopSelf();
		}

	}

	public boolean uploadfile(final String urlInput, String urlOutput) {

		final File file = new File(urlInput);
		showNotification("Cargando", (int) 100, (int) 0, file);
		try {
			FileInputStream inputStream = new FileInputStream(file);

			Entry mRequest = mDBApi.putFileOverwrite(urlOutput, inputStream,
					file.length(), new ProgressListener() {
						@Override
						public long progressInterval() {
							return 500;
						}

						@Override
						public void onProgress(long bytes, long total) {

							showNotification("Cargando", (int) total,
									(int) bytes, file);
							// Toast.makeText(ServicioUpdatePicture.this,
							// bytes+"", Toast.LENGTH_LONG).show();
						}
					});
			inputStream.close();

			if (mRequest != null) {
				return true;
			}

		} catch (DropboxException e) {
			// TODO Auto-generated catch block
			Toast.makeText(Servico2UpdatePictures.this, e.getMessage(),
					Toast.LENGTH_LONG).show();
			e.printStackTrace();
			return false;
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			Toast.makeText(Servico2UpdatePictures.this, e.getMessage(),
					Toast.LENGTH_LONG).show();
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			Toast.makeText(Servico2UpdatePictures.this, e.getMessage(),
					Toast.LENGTH_LONG).show();
			e.printStackTrace();
		}
		return false;
	}

	private String[] getKeys() {
		SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
		String key = prefs.getString(ACCESS_KEY_NAME, null);
		String secret = prefs.getString(ACCESS_SECRET_NAME, null);
		if (key != null && secret != null) {
			String[] ret = new String[2];
			ret[0] = key;
			ret[1] = secret;
			return ret;
		} else {
			return null;
		}
	}

	private AndroidAuthSession buildSession() {
		AppKeyPair appKeyPair = new AppKeyPair(APP_KEY, APP_SECRET);
		AndroidAuthSession session;

		String[] stored = getKeys();
		if (stored != null) {
			com.dropbox.client2.session.AccessTokenPair accessToken = new com.dropbox.client2.session.AccessTokenPair(
					stored[0], stored[1]);
			session = new AndroidAuthSession(appKeyPair, ACCESS_TYPE,
					accessToken);
		} else {
			session = new AndroidAuthSession(appKeyPair, ACCESS_TYPE);
		}

		return session;
	}

	private void showNotification(String Cadena, int max, int pro, File file) {
		CharSequence text = Cadena;

		Notification notification = new Notification(R.drawable.camera_unmount2,
				text, 1);
		PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
				new Intent(this, MainActivity.class), 0);
		notification.setLatestEventInfo(this, "Servicio Rastreo", text,
				contentIntent);
		// notification.flags = Notification.FLAG_FOREGROUND_SERVICE;

		RemoteViews contentView = new RemoteViews(getPackageName(),
				R.layout.notificacion);
		contentView.setProgressBar(R.id.progressBar1, max, pro, false);

		contentView.setImageViewResource(R.id.img, R.drawable.folder_upload);
		int percent = (int) (100.0 * (double) pro / max + 0.5);

		contentView.setTextViewText(R.id.textView1,
				"Uploading..... " + file.getName() + " (" + percent + "%)");
		notification.contentView = contentView;
		mNM.notify(R.string.hello_world, notification);

		// startForeground(1337,notification);

	}

	private void showNotificationError(String Cadena) {
		CharSequence text = Cadena;

		Notification notification = new Notification(R.drawable.error5, text,
				System.currentTimeMillis());

		PendingIntent contentIntent = PendingIntent.getService(this, 0,
				new Intent(this, Servico2UpdatePictures.class), 0);
		notification.setLatestEventInfo(this, "Servicio Rastreo", text,
				contentIntent);
		notification.flags = Notification.FLAG_ONGOING_EVENT;

		mNM.notify(R.string.hello_world, notification);
		// startForeground(R.string.hello_world, notification);

	}

	public void generateInsidencias(File file, Imagen img) {
		try {
			File fil = new File(file.getParentFile().getAbsolutePath(), img
					.getAplicacion().getPrevio().getReferencia()
					+ ".txt");

			if (fil.exists() == false) {
				fil.createNewFile();
			}

			PrintWriter out = new PrintWriter(new FileWriter(fil, true));
			// FileWriter writer = new FileWriter(gpxfile);

			out.write("/******Imagen " + img.getNombre() + "- Comentario: "
					+ img.getComentario() + " *****/ \n");
			out.flush();
			out.close();
			uploadfile(fil.getAbsolutePath(), img.getAplicacion().getCliente()
					.getCarpetaImagenes()
					+ img.getAplicacion().getPrevio().getReferencia()
					+ "/"
					+ img.getAplicacion().getPrevio().getReferencia() + ".txt");
			Toast.makeText(this, "Saved", Toast.LENGTH_SHORT).show();
		} catch (IOException e) {
			e.printStackTrace();

		}
	}

}
